package com.pig4cloud.pig.demo.Controller;

import com.alibaba.fastjson.JSON;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.demo.Service.UserService;
import com.pig4cloud.pig.demo.Util.ConstantWxUtil;
import com.pig4cloud.pig.demo.feign.Entity.User;
import io.itit.itf.okhttp.FastHttpClient;
import io.itit.itf.okhttp.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

@Controller
@RequestMapping("/api/ucenter/wx")
@Inner
public class WxLogin {

    @Autowired
    private UserService userService;

    @GetMapping("/callback")
    //@ResponseBody
    public String callback(String code, String state) {
        try {
            //获取accessToken的url
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtil.WX_OPEN_APP_ID,
                    ConstantWxUtil.WX_OPEN_APP_SECRET,
                    code
            );

            Response accessToken = FastHttpClient.get()
                    .url(accessTokenUrl)
                    .build()
                    .execute();

            Map<String, String> token = (Map) JSON.parse(accessToken.string());

            String access_token = token.get("access_token");
            String openid = token.get("openid");

            //获取用户信息的url
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";

            String userInfoUrl = String.format(
                    baseUserInfoUrl,
                    access_token,
                    openid
            );

            //模拟get请求
            Response userInfo = FastHttpClient.get()
                    .url(userInfoUrl)
                    .build()
                    .execute();

            //将json转成map
            Map<String, Object> userInfoMap = (Map) JSON.parse(userInfo.string());

            String nickname =(String) userInfoMap.get("nickname");
            String headimgurl =(String) userInfoMap.get("headimgurl");
            Integer sex =(Integer) userInfoMap.get("sex");


            User user = new User();
            user.setNickName(nickname);
            user.setAvatar(headimgurl);
            user.setAccount(nickname);
            user.setUsername(nickname);
            user.setPassword(nickname);
            user.setSex(sex);

            userService.insert(user);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:http://localhost:8989/#/all";
    }

    //生成微信扫描二维码
    @GetMapping("/wxlogin")
    @ResponseBody
    public R getWxCode() {
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        String redirect_url = ConstantWxUtil.WX_OPEN_REDIRECT_URL;

        try {
            //编码
            redirect_url = URLEncoder.encode(redirect_url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url = String.format(
                baseUrl,
                ConstantWxUtil.WX_OPEN_APP_ID,
                redirect_url,
                "article"
        );

        return R.ok(url);
    }
}
